<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Login extends WXController
{
    function __construct()
    {
        parent::__construct();
        $this->load->library('WxBase',null,'wxBase');
    }

    public function do_login()
    {
        $this->load->model('MUser');
        $re = $this->wxBase->login($this->param['code']);
        $safe_key = $this->create_safe_id(6);
        if ($re){
            $user = $this->MUser->getOne(['open_id' => $re['openid']]);
            if (!$user){
                $this->db->trans_start(); // 开启事务

                // 创建未绑定微信游客信息（包含openId）
                $obj = $this->MUser->createVo();
                $obj->safe_key = $safe_key;
                $obj->user_type = 1;
                $obj->open_id = $re['openid'];
                $obj->session_key = $re['session_key'];
                $obj->nick_name = '游客' . $this->create_safe_id(6);
                $obj->login_ip = $this->input->ip_address();
                $obj->login_time = time();
                $uid = $this->MUser->add($obj);
                if (!$uid){
                    $this->db->_trans_status = false;
                }
                // 生成用户token
                $token = $this->wxBase->generate_user_token($uid,30);
                $this->db->trans_complete();
                if ($this->db->_trans_status !== false){
                    $user = $this->MUser->getById($uid);
                    $user->token = $token['token'];
                    $user->expire_time = $token['expire_time'];
                    $this->ReturnJson(200,true,'登录成功',$user);
                }else{
                    $this->ReturnJson(1007,false,'登录失败',$re);
                }
            }else{
                // 已注册，返回用户信息以及token
                $user->session_key = $re['session_key'];
                if ($this->MUser->update($user)){
                    $token = $this->wxBase->generate_user_token($user->id,30);
                    $user->token = $token['token'];
                    $user->expire_time = $token['expire_time'];
                    $this->ReturnJson(200,true,'登录成功',$user);
                }else{
                    $this->ReturnJson(1007,false,'登陆失败，请稍后重试');
                }
            }
        }else{
            $this->ReturnJson(1007,false,'登陆失败，请稍后重试');
        }
    }
}
